import query from './atom/db/query';
import update from './atom/db/update';

declare const action_id: string;
declare const session_id: string;
declare const spaceid: string;

interface Message {
	class_id: string,
	exam_subjects_id: string,
	layout_no: string
}

async function atom(msg: Message) {
	const systemid = '5981';
	console.log(msg);
	const q1 = query(action_id, session_id, spaceid, systemid);
	//依据“考试科目编号”查<考场编排>得到“编排编号”（值多个)
	q1.prepare('arrange_exam_room', ['layout_no'], { exam_subjects_id: msg.exam_subjects_id }, 0, 1);
	const [arrange_exam_rooms] = await q1.exec();
	const layout_nos = arrange_exam_rooms.map((d: any) => {
		return d.layout_no;
	});
	console.log(layout_nos, '--<1>--');

	//依据“编排编号”（值多个）查<学生编排>得到“学号”（值多个）
	const q2 = query(action_id, session_id, spaceid, systemid);
	q2.prepare('arrange_exam_student', ['student_id'], { layout_no: { $in: layout_nos } }, 0, 1);
	const [arrange_exam_student] = await q2.exec();
	const student_ids = arrange_exam_student.map((d: any) => {
		return d.student_id;
	});
	console.log(student_ids, '--<2>--', JSON.stringify({ class_id: msg.class_id, student_id: { $in: student_ids } }));

	//依据“教学班编号”、“学号”过滤<教学班学生>，得到可分配学生数据
	const q3 = query(action_id, session_id, spaceid, '5991');
	q3.prepare('teachingclass_student', ['student_id', 'student_name', 'student_type', 'class_name', 'sex', 'student_no'], { class_id: msg.class_id, student_id: { $nin: student_ids } }, 0, 1);
	const [teachingclass_students] = await q3.exec();
	console.log(teachingclass_students, '--<3>--');

	//依据“编排编号”（地址栏中的编排编号），“学号”为空，查<学生编排>得到有未分配的座位。
	const q4 = query(action_id, session_id, spaceid, systemid);
	console.log(JSON.stringify({ layout_no: msg.layout_no, student_id: '' }));
	q4.prepare('arrange_exam_student', ['_id'], { layout_no: msg.layout_no, student_id: '' }, 0, 1);
	const [seats] = await q4.exec();
	console.log(seats, '--<4>--');

	//将可分配学生分配到未分配的座位上
	const { prepare, exec } = update(action_id, session_id, spaceid, systemid);
	const upd_data: any[] = [];
	seats.forEach((seat: any, i: number) => {
		if (teachingclass_students.length > i) {
			const student: any = teachingclass_students[i];
			if (student) {
				upd_data.push({
					_id: seat._id, student_name: student.student_name, student_id: student.student_id,
					student_type: student.student_type, sex: student.sex
				});
			}
		} else {
			console.log('学生人数不足');
		}
	});
	prepare('arrange_exam_student', upd_data);
	const ret = await exec();
	if (ret.code === 1) {
		return 'success';
	} else {
		return 'fail';
	}
}
